var ctx;
function setCtx(ctx) {
    this.ctx = ctx;
}
var status = false;
function setPayStatus(status){
	this.status = status;
}
var selTarget;
var rectAddr;
$(function(){
	$('.address-box').find('img').each(function(){
		var id = this.id;
		if(1 == id.split('_')[2]) {
			selTarget = this;
			rectAddr = id.split('_')[1];
		}
	})
	$('.person-info').click(function(){
		var tar = $(this).parent();
		$(tar).find('img').attr('src', ctx +'/images/qrdd/qr1.png');
		rectAddr = $(tar).find('img').attr('id').split('_')[1];
		$(selTarget).attr('src', ctx +'/images/qrdd/qr4.png');
		selTarget = $(tar).find('img');
	});
	
	$('#discout_tab').delegate('select[name=coupon_select]', 'change', function(){
		if('' == this.value) {
			
		} else {
			
			/**
			 * type: 1 -- 平台券
			 *       2 -- 店铺券
			 * 平台券和店铺券不能一起使用
			 */
			var param = this.value.split('_');
			var selId = $(this).attr('id');
			var selType = param[0];
			$('#discout_tab').find('select[name=coupon_select]').each(function(){
				var idTemp = $(this).attr('id').split('_');
				if($(this).attr('id') != selId){
					if(1 == selType) {
						this.options[0].selected = true;
					} else {
						if(1 == idTemp[0]){
							this.options[0].selected = true;
						}
					}
				}
			})
		}
		
		// 计算总优惠
		var couponAmount = 0;
		var couponIds = ''
		$('#discout_tab').find('select[name=coupon_select]').each(function(){
			if('' != this.value) {
				var values = this.value.split('_');
				couponAmount = Number(couponAmount).add(values[3]);
				if('' == couponIds) {
					couponIds = values[2];
				} else {
					couponIds = couponIds + "," + values[2];
				}
			}
		});
		$('#discountAmount').html(couponAmount);
		$('#couponAmount').val(couponAmount);
		$('#couponIds').val(couponIds);
		
		// 应付款 = 订单总额 - 优惠金额 + 配送费
		var total = $('#total').val();
		var coupon = $('#couponAmount').val();
		var carriage = $('#carriageTotal_hidden').val();
		$('#realTotalHtml').html(Number(Number(total).sub(coupon)).add(carriage));
		$('#realTotal').val(Number(Number(total).sub(coupon)).add(carriage));
		
//		var total = $('#total').val();
//		$('#realTotalHtml').html((Number(total).sub(couponAmount)).add($('#carriageTotal_hidden').val()));
//		$('#realTotal').val((Number(total).sub(couponAmount)).add($('#carriageTotal_hidden').val()));
    });
	
	$('.order-list').delegate('select[name=dist_type]', 'change', function(){
		var param = this.id.split('_')
		switch (this.value) {
		case "0":
			$('#carriage_' + param[0]).html($('#shop_carriage_' + param[0]).val());
			
			var preCarriage = $('#carriageTotal_hidden').val();
			var addValue = Number(param[1]).sub(param[2]);
			$('#carriage_total').html(Number(preCarriage).add(addValue));
			$('#carriageTotal_hidden').val(Number(preCarriage).add(addValue))
			break;
		case "1":
			$('#carriage_'  + param[0]).html('0');
			var preCarriage = $('#carriageTotal_hidden').val();
			var addValue = Number(param[1]).sub(param[2]);
			$('#carriage_total').html(Number(preCarriage).sub(addValue));
			$('#carriageTotal_hidden').val(Number(preCarriage).sub(addValue))
			break;
		default:
			break;
		}
		
		// 应付款 = 订单总额 - 优惠金额 + 配送费
		var goodsType = $('#goodsType').val();
		
		var total = $('#total').val();
		if(2 == goodsType) {
			total = 0;
		}
		var coupon = $('#couponAmount').val();
		var carriage = $('#carriageTotal_hidden').val();
		$('#realTotalHtml').html(Number(Number(total).sub(coupon)).add(carriage));
		$('#realTotal').val(Number(Number(total).sub(coupon)).add(carriage));
	});
	
	
	
	$('.new-add').click(function() {
		var shopcartIds = $('#shopcartIds').val();
		var index = parent.layer.getFrameIndex(window.name);
		layer.open({
			title: false,
			type: 2,
			content: ctx + '/shopcart/addAddress',
			area: ["800px","500px"],
	      	btn: ['确定', '取消']
		    	,yes: function(index, layero){ //或者使用btn1
		        	//按钮【按钮一】的回调
		    		var iframeWin = window[layero.find('iframe')[0]['name']];
		    		var result = iframeWin.saveAddress();
		    		if(result) {
		    			layer.close(index);
		    		}
		    	},cancel: function(index){ //或者使用btn2
		        	//按钮【按钮二】的回调
		    	},
				end: function(){
					location.href = ctx + "/shopcart/confirmOrder?shopcartIds=" + shopcartIds + "&type=" + $('#goodsType').val();
				}
			});
	});
	
	$(".pay-btn").click(function() {
		if(undefined == rectAddr) {
			layer.msg("请选择收货地址", {
				icon : 1,
				time : 1000
			});
			return;
		}
		var payType = $('.pay-type-box').find("input[type=checkbox]:checked").val();
		if(undefined == payType) {
			layer.msg("请选择支付方式", {
				icon : 1,
				time : 1000
			});
			return;
		}
		var shopcartId = $('#shopcartIds').val();
		var couponAmount = $('#couponAmount').val();
		var goodsType = $('#goodsType').val();
		var orderInfo = new Array();
		$("input[name='receive_time']").each(function(){
		    var info = {};
			receiveTime = $(this).val();
			var tar = $(this).parent().parent();
			var message = $(tar).find(':input:eq(0)').val();
			var distType = $(tar).find('option:selected').val();
			info.shopMsg = message;
			info.isBySelf = distType;
			info.expectTime = receiveTime;
			info.shopId = $(this).attr('id');
			info.carriage = $('#carriageTotal_hidden').val();
			info.couponPrice = couponAmount;
			info.totalPrice = $('#total').val();
			info.couponId = $('#couponIds').val();
			info.rectAddrId = rectAddr;
			orderInfo.push(info);
		});
		$.ajax({
			type: "POST",
			url: ctx + "/shopcart/sumbitOrder?shopcartIds=" + shopcartId + "&type=" + goodsType,
		   	data: JSON.stringify(orderInfo),//将对象序列化成JSON字符串
		   	dataType:"json",
		   	contentType : 'application/json;charset=utf-8', //设置请求头信息
			success: function(data){
			    if(data.success) {
			        if(1== data.resultCode) {
			            if(1 == payType) {
			                $.ajax({
			                    type: "POST",
			                    url: ctx + '/pay/aliPay',
			                    dataType : 'json',
			                    data:{
			                        type:1,
			                        outTradeNo:data.obj
			                    },
			                    success: function(data){
			                        $('#returnAli').append(data.sHtmlText);
			                    },
			                    error: function(res){
			                    }
			                });
			            } else if(2 == payType) {
			                layer.open({
			                    type: 2,
			                    title: '微信支付',
			                    content: ctx + "/views/mall/pay_complete.jsp?orderNumber=" + data.obj,
			                    skin: "house-add",
			                    area: ["505px","380px"],
			                    end: function(){
			                        location.href = ctx + '/shopcart/shopcartList';
			                    }
			                });
			            }
			        } else {
			            location.href = ctx + '/shopcart/shopcartList'
			        }
			    } else {
			        layer.msg(data.msg, {
		                icon : 1,
		                time : 2000
		            });
			    }
			},
			error: function(res){
			}
		});

		
//		layer.open({
//			type: 2,
//			title: '微信支付',
//			content: ctx + "/shopcart/sumbitOrder?shopcartIds=" + shopcartId + "&orderInfo=" +users,
//			skin: "house-add",
//			area: ["505px","380px"],
//			end: function(){
//				if(!status){
//					location.href = ctx + '/shopcart/shopcartList';
//				}
//			}
//		});
	});
});

var isShow = false;
function selectCoupon(shopId) {
	if(!isShow) {
		$('#coupon_src').attr('src', ctx + '/images/qrdd/yhj1.png');
		isShow = true;
		$('#discout_tab').show();
//		$('#discout_tab').delegate('select[name=coupon_select]', 'change', function(){
//	    	alert(this.value);
//	    });
	} else {
		$('#coupon_src').attr('src', ctx + '/images/qrdd/yhj2.png');
		isShow = false;
		$('#discout_tab').hide();
	}
	
	var shopIds = '';
	$('input[name="shopId"]').each(function(){
		shopIds = shopIds + $(this).val() + ',';
	});
	
	
//	$.post(ctx + "/shopcart/updateAmount", {
//        id : ss[0],
//        sub : sub,
//        price : price,
//        amount : cur,
//    }, function(data) {
//        if (data.success) {
//            var beforeSub = $('#hiddenTotalPrice').val();
//            var after = Number(beforeSub).add(Number(price).mul(sub));
//            if(!$(mEl).prop('checked')){
//                after = Number(beforeSub).add(Number(price).mul(cur));
//            }
//            $('#totalPrice').html('￥' + after);
//            $('#hiddenTotalPrice').val(after);
//            $(obj).val(cur);
//            
//            // udpate checkbox id
//            var preId = $(mEl).attr('id');
//            preId = preId.substring(0, preId.lastIndexOf('_') + 1) + cur;
//            $(mEl).attr('id',preId);
//            me.toggleCheckbox(1, true, mEl);
//        } else {
//            layer.msg(data.msg, {
//                icon : 2,
//                time : 2000
//            });
//        }
//        doing = false;
//    });
	
	return;
}

function checkPayType(target){
	if(1 == target.value) {
		$('#wxPay').prop('checked', false);
	} else {
		$('#aliPay').prop('checked', false);
	}
}